﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using MQTT.Server.Host.WebAPI.Models;

namespace MQTT.Server.Host.WebAPI.Controller
{
    public class DeviceControlController : ApiController
    {
        private const string ControlTopic = "$kvc";
        [HttpGet]
        [ActionName("on")]
        public ApiResponse On(string tag)
        {
            ApiResponse response = new ApiResponse();
            response.Code = ResponseCode.Success;
            try
            {
                App.server.Publish(ControlTopic, GetMessage(tag, true));
            }
            catch (Exception e)
            {
                response.Code = ResponseCode.Error;
                response.Data = e.StackTrace;
            }
            return response;
        }

        [HttpGet]
        [ActionName("off")]
        public ApiResponse Off(string tag)
        {
            ApiResponse response = new ApiResponse();
            try
            {
                App.server.Publish(ControlTopic, GetMessage(tag, false));
            }
            catch (Exception e)
            {
                response.Code = ResponseCode.Error;
                response.Data = e.StackTrace;
            }
            response.Code = ResponseCode.Success;
            return response;
        }


        private string GetMessage(string tag, bool isOpen)
        {
            int operation = isOpen ? 1 : 0;
            var result = $"{{\"w\":[{{\"tag\":\"{tag}\",\"value\":{operation}}}],\"ts\":\"{DateTime.Now:O}\"}}";
            return result;
        }


    }
}
